<?php

namespace app\admin\controller\meter;

use app\common\controller\Backend;

use think\Controller;
use think\Model;
use think\Request;
use fast;
use fast\Http;

/**
 * 仪表管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * @var Model
     */
    protected $model = null;
    protected $projectModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Meter');
        $this->projectModel = model('MeterProject');
        $this->communityModel = model('community');
        $this->view->assign('project', $this->projectModel->field('id,name')->select());
        $this->view->assign('community', $this->communityModel->field('code,name')->select());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('project')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        return parent::create('form');
    }

    public function edit($ids = NULL)
    {
        return parent::modify($ids, 'form');
    }

    public function del($ids = null)
    {
        $where = array(
            'id' => array('in', $ids)
        );
        parent::delete($where);
    }

    public function sycndata()
    {
        $id = input('post.id', 0);
        $c = $this->sycnLog($id);
        $this->success('同步了' . $c . '条抄表记录');
        // $meter = $this->model->where('id', $id)->find();
        // $maddr = $meter['maddr'];
        // if ($maddr == '') {
        //     $url = 'http://218.205.108.103:7777/TPWebService.asmx/GetMArchivesByUserNo';
        //     $data_string = '{ "userNo":"' . $meter['userno'] . '"}';
        //     $options = [
        //         CURLOPT_HTTPHEADER => [
        //             'Content-Type: application/json; charset=utf-8',
        //             'Content-Length:' . strlen($data_string)
        //         ]
        //     ];
        //     $rest = Http::post($url, $data_string, $options);
        //     if (strlen($rest) > 1) {
        //         $json = json_decode($rest);
        //         $data = json_decode($json->d);
        //         $maddr = $data[0]->MeterAddr;
        //         $meter['maddr'] = $maddr;
        //         $meter->save();
        //         // var_dump($data[0]->MeterAddr);

        //     } else {
        //         return;
        //     }
        // }


        // $url = 'http://218.205.108.103:7777/TPWebService.asmx/GetMFreezeData';
        // $data_string = '{
        //     "mAddr":"' . $maddr . '",
        //     "code":"FROZENMETERVALUE",
        //     "sTime":"2021-11-01",
        //     "eTime":"2021-12-01"
        //     }';
        // $options = [
        //     CURLOPT_HTTPHEADER => [
        //         'Content-Type: application/json; charset=utf-8',
        //         'Content-Length:' . strlen($data_string)
        //     ]
        // ];
        // $rest = Http::post($url, $data_string, $options);
        // if (strlen($rest) > 1) {
        //     $json = json_decode($rest);
        //     $datas = json_decode($json->d);

        //     $mydatas = [];
        //     $modelLog = model('MeterLog');
        //     foreach ($datas as $key) {
        //         // print $key->TotalRate."\n";

        //         $arr = [
        //             'meter_id' => $id,
        //             'meter_type' => $meter['meter_type'],
        //             'value' => $key->TotalRate,
        //             'create_time' => strtotime($key->TerReadTime),
        //             'update_time' => strtotime($key->TerReadTime)
        //         ];
        //         $d = $modelLog->where($arr)->find();
        //         if ($d == null) {
        //             array_push($mydatas, $arr);
        //         }
        //        // var_dump($d);
        //         // $modelLog =model('MeterLog');
        //         // $modelLog['meter_id']=$id;
        //         // $modelLog['meter_type']=$meter['meter_type'];
        //         // $modelLog['value']=$key->TotalRate;
        //         // $modelLog['create_time']=strtotime($key->TerReadTime);
        //         // $modelLog['update_time']=strtotime($key->TerReadTime);
        //         // $modelLog->save();
        //         // $modelLog->save(
        //         //     [
        //         //         'meter_id'=>$id,
        //         //         'meter_type'=>$meter['meter_type'],
        //         //         'value'=>$key->TotalRate,
        //         //         'create_time'=>strtotime($key->TerReadTime),
        //         //         'update_time'=>strtotime($key->TerReadTime)
        //         //     ]
        //         // );
        //     }

        //     $modelLog->insertAll($mydatas);
        //     
        //     //var_dump($mydatas);
        // }
    }

    //同步所有的记录
    public function sycnAll()
    {
        $meterList = $this->model->where('community_code', 'CM2021072000001')->select();
        foreach ($meterList as $key) {
            $this->sycnLog($key['id']);
        }
    }

    public function sycnLog($id)
    {
        $re = -1;
        $meter = $this->model->where('id', $id)->find();
        $maddr = $meter['maddr'];
        if ($maddr == '') {
            $url = 'http://218.205.108.103:7777/TPWebService.asmx/GetMArchivesByUserNo';
            $data_string = '{ "userNo":"' . $meter['userno'] . '"}';
            $options = [
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length:' . strlen($data_string)
                ]
            ];
            $rest = Http::post($url, $data_string, $options);
            if (strlen($rest) > 1) {
                $json = json_decode($rest);
                $data = json_decode($json->d);
                $maddr = $data[0]->MeterAddr;
                $meter['maddr'] = $maddr;
                $meter->save();
                // var_dump($data[0]->MeterAddr);

            } else {
                return;
            }
        }
        $eTime = date("Y-m-d");
        $sTime = date("Y-m-d", strtotime("last month"));

        $url = 'http://218.205.108.103:7777/TPWebService.asmx/GetMFreezeData';
        $data_string = '{
            "mAddr":"' . $maddr . '",
            "code":"FROZENMETERVALUE",
            "sTime":"' . $sTime . '",
            "eTime":"' . $eTime . '"
            }';
        $options = [
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data_string)
            ]
        ];
        $rest = Http::post($url, $data_string, $options);
        if (strlen($rest) > 1) {
            $json = json_decode($rest);
            $datas = json_decode($json->d);

            $mydatas = [];
            $modelLog = model('MeterLog');
            foreach ($datas as $key) {
                // print $key->TotalRate."\n";

                $arr = [
                    'meter_id' => $id,
                    'meter_type' => $meter['meter_type'],
                    'value' => $key->TotalRate,
                    'create_time' => strtotime($key->TerReadTime),
                    'update_time' => strtotime($key->TerReadTime)
                ];
                $d = $modelLog->where($arr)->find();
                if ($d == null) {
                    array_push($mydatas, $arr);
                }
                // var_dump($d);
                // $modelLog =model('MeterLog');
                // $modelLog['meter_id']=$id;
                // $modelLog['meter_type']=$meter['meter_type'];
                // $modelLog['value']=$key->TotalRate;
                // $modelLog['create_time']=strtotime($key->TerReadTime);
                // $modelLog['update_time']=strtotime($key->TerReadTime);
                // $modelLog->save();
                // $modelLog->save(
                //     [
                //         'meter_id'=>$id,
                //         'meter_type'=>$meter['meter_type'],
                //         'value'=>$key->TotalRate,
                //         'create_time'=>strtotime($key->TerReadTime),
                //         'update_time'=>strtotime($key->TerReadTime)
                //     ]
                // );
            }

            $modelLog->insertAll($mydatas);
            $re = count($mydatas);
        }
        return $re;
    }
}
